package com.ubi.core.base;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 公共servie
 * 
 * @author : lvh
 * @date: 16-01-29
 */
public abstract class BaseService<M, P> {

    // 公共字段
    // 新增时间
    public static final String CREATE_DATE = "createDate";

    // 新增人员
    public static final String CREATE_BY = "createBy";

    // 更新时间
    public static final String MODIFY_TIME = "updateDate";

    // 更新人员
    public static final String UPDATE_BY = "updateBy";

    // 删除标志
    public static final String DEL_FLAG = "delFlag";

    protected abstract GenericMapper<M, P> getMapper();

    protected void beforeUpdate(M model) {

        try {
            BeanUtils.setProperty(model, MODIFY_TIME, new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void beforeAdd(M model) {

        try {
            BeanUtils.setProperty(model, CREATE_DATE, new Date());
            BeanUtils.setProperty(model, DEL_FLAG, Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void beforeDelete(M model) {

        try {
            BeanUtils.setProperty(model, DEL_FLAG, Boolean.FALSE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public int add(M model) {

        beforeAdd(model);
        return getMapper().insert(model);
    }

    @Transactional
    public int delete(M model) {

        beforeDelete(model);
        return getMapper().updateByPrimaryKeySelective(model);
    }

    @Transactional
    public int update(M model) {

        beforeUpdate(model);
        return getMapper().updateByPrimaryKeySelective(model);
    }

    public M find(P pk) {

        return getMapper().selectByPrimaryKey(pk);
    }

    @Transactional
    public int save(M model, P pk) {

        int result = 0;
        if (pk == null) {
            result = this.add(model);
        } else {
            M m = getMapper().selectByPrimaryKey(pk);
            if (m == null) {
                result = this.add(model);
            } else {
                result = this.update(model);
            }
        }

        // afterChange();
        return result;
    }

    protected void afterChange() {

    }

}
